import json
import time

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 配置 Chrome 选项
options = Options()
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(options=options)
driver.maximize_window()


def login(base_url):
    driver.get(base_url)
    time.sleep(1)
    driver.execute_script('window.scrollTo(0, 200)')  # 遇见了反爬行为，通过滚动页面对抗
    username = "13721071025"
    password = "ZHANGdawei69.."
    driver.find_element(By.XPATH, '//*[@id="app"]/div/div/div[2]/div[2]/form/div[1]/input').send_keys(username)
    time.sleep(3.2)
    driver.find_element(By.XPATH, '//*[@id="app"]/div/div/div[2]/div[2]/form/div[2]/input').send_keys(password)
    time.sleep(2.11)
    # 点击登录
    driver.find_element(By.XPATH, '//*[@id="app"]/div/div/div[2]/div/button').click()
    time.sleep(120)
    cookies = driver.get_cookies()  # 获取cookie,列表形式
    f1 = open('cookies.txt', 'w')
    f1.write(json.dumps(cookies))
    f1.close()
    driver.close()


if __name__ == '__main__':
    # 模拟登陆-给定登陆的网址
    base_url = "https://passport.weibo.cn/signin/login"
    login(base_url)
    print("新浪微博登陆成功！")
